package com.bc.plugin.doc.base.impl;

import com.bc.plugin.doc.base.BaseRequestParamHandler;
import com.bc.plugin.doc.resolver.ApiParamResolver;
import com.power.common.util.StringUtil;
import com.power.doc.constants.DocAnnotationConstants;
import com.power.doc.model.ApiParam;
import com.power.doc.utils.DocClassUtil;
import com.thoughtworks.qdox.model.JavaAnnotation;
import com.thoughtworks.qdox.model.JavaParameter;
import com.thoughtworks.qdox.model.expression.AnnotationValue;

import java.util.List;
import java.util.Map;

/**
 * @author xhh 2019/11/21
 */
public class DefaultRequestParamHandler extends BaseRequestParamHandler {

    @Override
    public List<ApiParam> handle(JavaParameter parameter, Map<String, String> paramsComments, ApiParamResolver apiParamResolver, boolean isStrict) {
        String typeName = parameter.getType().getGenericCanonicalName();
        String paramName = parameter.getName();
        String fullTypeName = parameter.getType().getFullyQualifiedName();
        if (DocClassUtil.isMvcIgnoreParams(typeName)) {
            return null;
        }
        if (!paramsComments.containsKey(paramName) && DocClassUtil.isPrimitive(fullTypeName) && isStrict) {
            throw new RuntimeException("ERROR: Unable to find javadoc @param for actual param \"");
        }
        List<JavaAnnotation> annotations = parameter.getAnnotations();
        boolean isRequired = true;

        for (JavaAnnotation annotation : annotations) {
            AnnotationValue annotationRequired = annotation.getProperty(DocAnnotationConstants.REQUIRED_PROP);
            if (null != annotationRequired) {
                isRequired = Boolean.valueOf(annotationRequired.toString());
            }
            String annotationName = annotation.getType().getName();
            if (DocAnnotationConstants.REQUEST_PARAM.equals(annotationName) ||
                    DocAnnotationConstants.SHORT_PATH_VARIABLE.equals(annotationName)) {
                AnnotationValue annotationValue = annotation.getProperty(DocAnnotationConstants.VALUE_PROP);
                if (null != annotationValue) {
                    paramName = StringUtil.removeQuotes(annotationValue.toString());
                }
                AnnotationValue annotationOfName = annotation.getProperty(DocAnnotationConstants.NAME_PROP);
                if (null != annotationOfName) {
                    paramName = StringUtil.removeQuotes(annotationOfName.toString());
                }
            }
        }
        return apiParamResolver.resolverRequestParams(typeName, paramName, paramsComments, isRequired);
    }
}
